package com.rh.number.util;

import com.rh.number.entity.UserinfoEntity;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;

@Component
public class JwtUtil {
    private final SecretKey key = Jwts.SIG.HS256.key().build();
    private final long expiration = 360000000; // 1小时

    public String generateToken(UserinfoEntity user) {
        return Jwts.builder()
                .subject(user.getUsername())
                .claim("role", user.getRole())
                .expiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(key)
                .compact();
    }

    public Claims parseToken(String token) {
        return Jwts.parser()
                .verifyWith(key)
                .build()
                .parseSignedClaims(token)
                .getPayload();
    }
    // 增强验证方法
    public Claims validateToken(String token) throws JwtException {
        try {
            return Jwts.parser()
                    .verifyWith(key)
                    .build()
                    .parseSignedClaims(token)
                    .getPayload();
        } catch (ExpiredJwtException ex) {
            throw ex;  // 单独处理过期异常
        } catch (JwtException | IllegalArgumentException ex) {
            throw new MalformedJwtException("无效令牌", ex);
        }
    }

    public String getUsernameFromToken(String token) {
        return parseToken(token).getSubject();
    }


}